package com.hqyj.ctxp.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.hqyj.ctxp.pojo.User;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import java.util.Date;

/**
 * @className: JwtUtils
 * @description: TODO 类描述
 * @author: mmm
 * @date: 2022/12/5
 **/
public class JwtUtils {
    //过期时间， 一天
    private static final Long EXPIRES_TIME = 1000L*60*60*24;
    //
    private static final String TOKEN_SALT = "mmm";

    /*
     * 创建用户令牌
     */
    public static String createUserToken(User user, long expTime){
        Date nowDate = new Date();
        Date expDate = new Date(System.currentTimeMillis()+ expTime);

        return JWT.create().withAudience(user.getUserNo() + "") // 签发对象
                .withIssuedAt(nowDate) // 发行时间
                .withExpiresAt(expDate) // 有效期
                .withClaim("userNo", user.getUserNo()) // Payload 载荷，可按官方推荐，也可自定义，可有多个
                .withClaim("userName", user.getUserName())
                .sign(Algorithm.HMAC256(user.getUserNo() + TOKEN_SALT)); // 使用 HMAC256 加密算法，生成签名
    }

    public static String createUserToken(User user) {
        return createUserToken(user, EXPIRES_TIME);
    }

    /*
    * 获取令牌中的签发对象
    * */
    public static String getAudience(String token){
        String audience = null;
        try{
            audience = JWT.decode(token).getAudience().get(0);
        }catch (Exception e){
            e.printStackTrace();
        }
        return audience;
    }

    /*
     *  用签发对象验证令牌
     */
    public static DecodedJWT verifyToken(String token, String secret) {
        DecodedJWT decodedJWT = null;
        try {
            JWTVerifier jWTVerifier = JWT.require(Algorithm.HMAC256(secret + TOKEN_SALT)).build();
            decodedJWT = jWTVerifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return decodedJWT;
    }

    /*
     *  根据名字获取载荷内容
     */
    public static Claim getClaimByName(String token, String claimName) {
        return JWT.decode(token).getClaim(claimName);
    }

    public static void main(String[] args) {
        User user = new User();
        user.setUserNo(101);
        user.setUserName("zs");
        String token = JwtUtils.createUserToken(user);
        System.out.println(token);
        System.out.println(JwtUtils.verifyToken(token, user.getUserNo() + "").getClaims());
        System.out.println(JwtUtils.verifyToken(token, "2"));
        System.out.println(JwtUtils.getAudience(token));//101
        System.out.println(JwtUtils.getClaimByName(token, "userNo")); //"101"
        System.out.println(JwtUtils.getClaimByName(token, "userName")); //"zs"
    }
}
